<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
	
<%@ taglib prefix="spring" uri="/WEB-INF/tlds/spring.tld"%>
<%@ taglib prefix="c" uri="/WEB-INF/tlds/c.tld"%>
<c:set var="BasePath" value="${pageContext.request.contextPath}"></c:set>
<c:set var="Plugins" value="${pageContext.request.contextPath}/res/plugins"></c:set>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品添加页面</title>

<link href="${Plugins}/ligerUI/skins/Aqua/css/ligerui-all.css" rel="stylesheet" type="text/css" />
<link href="${Plugins}/ligerUI/skins/ligerui-icons.css" rel="stylesheet" type="text/css" />
<script src="${Plugins}/jquery/jquery-1.4.4.min.js"	type="text/javascript"></script>
<script src="${Plugins}/ligerUI/js/ligerui.min.js" type="text/javascript"></script>
<script src="${Plugins}/jquery-validation/jquery.validate.min.js" type="text/javascript"></script>
<script src="${Plugins}/jquery-validation/jquery.metadata.js" type="text/javascript"></script>
<script src="${Plugins}/jquery-validation/messages_cn.js" type="text/javascript"></script>
<script src="${BasePath}/res/js/common/jquery.form.js" type="text/javascript"></script>
<script src="${BasePath}/res/js/common/jquery.validate.method.js" type="text/javascript"></script>
<script type="text/javascript" src="${BasePath}/res/js/ligerCommon.js"></script>
<script src="${BasePath}/res/js/product/commodityCat.js" type="text/javascript"></script>
<script type="text/javascript" src="${BasePath}/res/js/json2.js"></script>
<style type="text/css">
    body{ font-size:12px;}
    .l-table-edit {}
    .l-table-edit-td{ padding:4px;}
    .l-button-submit,.l-button-test{width:80px; float:left; margin-left:10px; padding-bottom:2px;}
    .l-verify-tip{ left:230px; top:120px;}
    .navbar {
		height: 20px;
		border-bottom: #E6E6E6 solid 1px;
		line-height: 20px;
	}
	.p-tab .s-lab{font-size:12px;font-family:"微软雅黑",​"宋体",​Arial,​sans-serif;}
	input.l-textarea{width:170px;height:20px;font-size:12px;}
	
	.errorcss{border-color:red;}
	
</style>
</head>


<body style="padding:10px">
<div class="navbar">
		<span>您当前的位置：</span>
		商品管理 &gt; 商品列表 &gt; 新增商品
</div>
<form name="form1" action="add_commo.do" method="post" id="form1">
<input type="hidden" id="productString" name="productString" >

<table cellpadding="0" cellspacing="0" class="l-table-edit p-tab"" >
	<tr>
        <td align="right" class="l-table-edit-td s-lab"><font color="red">*</font> 商品分类：</td>
        <td align="left" class="l-table-edit-td s-lab">
	    	<input type="hidden" id="catNo" name="catNo" value="${catNo }">
			<div id="catDiv"></div>
        </td>
        <td align="left"></td>
    </tr>
    
    <tr>
        <td align="right" class="l-table-edit-td s-lab"><font color="red">*</font>商品名称：</td>
        <td align="left" class="l-table-edit-td "><input name="commoName" type="text" id="commoName" class="l-textarea"  validate="{required:true,rangelength:[1,30]}" /></td>
        <td align="left"></td>
    </tr>
	
     <tr>
        <td align="right" class="l-table-edit-td s-lab" ><font color="red">*</font>商品类型：</td>
        <td align="left" class="l-table-edit-td s-lab"> 
        <input type="radio" name="commoType" value="0" checked="true" />实体商品
        <!-- <input type="radio" name="commoType" value="1" />赠品
		<input type="radio" name="commoType" value="2" />免费货 -->
		<input type="radio" name="commoType" value="3" />虚拟商品
        </td><td align="left"></td>
    </tr>
    
     <tr>
        <td align="right" class="l-table-edit-td s-lab" ><font color="red">*</font>品牌：</td>
     	 <td align="left" class="l-table-edit-td s-lab"> 
     	 <select name="brandNo" id="brandNo"><option value="0">请选择品牌</option></select>
        </td>
        <td align="left"></td>
    </tr>
    	
    <tr>
        <td align="right" class="l-table-edit-td s-lab">商品描述：</td>
        <td align="left" class="l-table-edit-td"><textarea class="l-textarea"  onkeyup="this.value=this.value.substring(0,1000);" style="width: 800px;height: 100px;" name="description"  validate="{required:false,rangelength:[1,1000]}"></textarea>
        </td><td align="left"></td>
    </tr>
	</table>
	<br />
	<div><font color="red">*</font>请选择货品规格:</div>
	<div id="choosespecDiv" style="margin-top: 10px;"></div><br />	
		
	
	<!--  <div style="margin-top:15px;"><input type="button" onclick="getProd()" value="货品"></div> -->
	<div id="maingrid" style="margin:0; padding:0"></div>
	
	
<input type="submit" value="保存" id="submit1" class="l-button l-button-submit" /> 
<input type="button" value="取消" name="tests" id="tests" class="l-button l-button-test" />
</form>	
</table>
<script type="text/javascript">

var grid = "";

/* var saleTypeData = [{saleType:1,text:"购销"},{saleType:2,text:"代销"}]; */
 var saleTypeData = [{saleType:1,text:"购销"}];
 var inventoryTypeData = [{inventoryType:1,text:"实库"},{inventoryType:2,text:"虚库"}]; 
 //var inventoryTypeData = [{inventoryType:1,text:"实库"}];
 var inventoryType=1;
 var saleType=1;
 var commoType=$("#form1").find("input[name=commoType]:checked").val();
 
 $("#form1").find("input[name=commoType]").change(function(){
	 if($(this).val()==3){
		 inventoryTypeData=[{inventoryType:2,text:"虚库"}];
		 inventoryType=2;
	 }else{
		 inventoryType=1
	 }
     for(var x in grid.getData()){
		 	grid.updateRow(grid.getRow(x),{inventoryType:inventoryType});
     }
 }); 
 if(commoType==3){
	 inventoryTypeData=[{inventoryType:2,text:"虚库"}]; 
	 inventoryType=2
 }
var inventory = null;
var data = [{prodBarCode: "",saleType: saleType,inventoryType: inventoryType,salePrice: "",prodRate:"",unSalePrice:"",buyNum:"",casePakgSize: "",prodUnit:""}];
$(function() {
	grid = $("#maingrid").ligerGrid({
	    columns: [
	    { display: '货品条码', name: 'prodBarCode',
	    	editor: {type: 'text',onChange:function(rowcell, value){valProdBarCode(rowcell, value)}},
	    	render: function (rowdata, rowindex, value){
	    		if(codeid != -1 && codeid == rowindex){
	    			value = "";
	    		}else{
	    			value = value.substring(0,14);
	    		}
	    		if(!/^\w+$/.test(value) && value!= ""){
	    			alert("输入的条码不符合条码规范！!");
	    			value = "";
	    		}	
	    		rowdata.prodBarCode = value;
	    		return value;
	    	}
	    },
	    { display: '销售类型', name: 'saleType',//editor: { type: 'select', data: saleTypeData, valueField: 'saleType' },
            render: function (item,index,value)
            {
            	/* if(item["inventoryType"] == 2 && value == 1){
	    			$.ligerDialog.warn("购销货品库存不可以是虚库");
	    			value = item.saleType = "";
	    		} */
                switch (parseInt(value)) {
				case 1:
					return "购销";
					break;
				case 2:
					return "代销";
					break;
				default:
					return "请选择";
					break;
				}
            }
	    },
	    { display: '库存类型', name: 'inventoryType',//editor: { type: 'select',name:"sss", data: inventoryTypeData, valueField: 'inventoryType' },
        	render: function (item,index,value)
            {
        		/* if(item["saleType"] == 1 && value == 2){
	    			$.ligerDialog.warn("购销货品库存不可以是虚库");
	    			value = item.inventoryType = "";
	    		} */
            	switch (parseInt(value)) {
    			case 1:
    				return "实库";
    				break;
    			case 2:
    				return "虚库";
    				break;
    			default:
    				return "请选择";
    				break;
    			}
            }
	    },
	   
	    { display: '含税零售价', name: 'salePrice',type:'float',editor: { type: 'float',minValue:0 },
	    	render: function (rowdata, rowindex, value){
	    		if(isNaN(value)) value = 0;
	    		if(value > 0){
            		value = String(value).substr(0,10);
            	}
	    		rowdata.salePrice = value;
	    		rowdata.unSalePrice = (Number(rowdata.salePrice)/Number(1+Number(rowdata.prodRate)/100)).toFixed(2);
	    		return value;
	    	}
	    },
	    { display: '税率(%)', name: 'prodRate',type:'float',editor: { type: 'float',minValue:0,maxValue:100 },
	    	render: function (rowdata, rowindex, value){
	    		if(isNaN(value) || value > 100 || value <0){
	    			$.ligerDialog.warn("请输入0-100范围内的数字!");
	    			value = '0';
	    		}
	    		var num = new Number(value);
	    		return rowdata.prodRate = num.toFixed(2);
	    	}
	    },
	    { display: '未税零售价', name: 'unSalePrice',type:'float',editor: { type: 'float',minValue:0 },
	    	render: function (rowdata, rowindex, value){
	    		if(isNaN(value)) value = 0;
	    		if(value > 0){
            		value = String(value).substr(0,10);
            	}
	    		return rowdata.unSalePrice = value;
	    		
	    	}
	    },
	    { display: '最低订货数量', name: 'buyNum',type: 'int',editor: { type: 'int',minValue:0 },
	    	render:function(rowdata, rowindex, value){
	    		if(isNaN(value)) value = 0;
	    		if(value > 0){
            		value = String(value).substr(0,10);
            	}
	    		return rowdata.buyNum = value;
        	}
	    },
	    { display: '箱包装规格', name: 'casePakgSize',editor: { type: 'text' },
	    	render: function (rowdata, rowindex, value){
	    		if(value!=''){
	    			value = value.substring(0,15);
	    		}
	    		rowdata.casePakgSize = value;
	    		return value;
	    	}	
	    
	    },
	    { display: '单位', name: 'prodUnit',editor: { type: 'text' },
	    	render: function (rowdata, rowindex, value){
	    		if(value!=''){
	    			value = value.substring(0,15);
	    		}
	    		rowdata.prodUnit = value;
	    		return value;
	    	}		
	    },
	    { display: '操作', isSort: false, render: function (rowdata, rowindex, value){
	       	var  text = '<a href="javascript:deleteProduct('+rowindex+');">删除</a>';
	        return text;
	    	}
	    }
	    ],
	    width:"100%",height:"100%",
	    usePager: false,enabledEdit: true,rownumbers:false,
	    data: $.extend(true,{},{"Rows":data}),
	    toolbar:{items: [{ text: "新增货品", click: addProduct, icon: "add" }]}
	});
});

//添加行
function addProduct() {
	var manager = $("#maingrid").ligerGetGridManager();
	manager.addRow({prodBarCode: "",saleType: saleType,inventoryType: inventoryType,salePrice: "",prodRate:"",unSalePrice:"",buyNum:"",casePakgSize: "",prodUnit:""});
	grid.loadData();
}

//删除行
function deleteProduct(rowindex) {
	var manager = $("#maingrid").ligerGetGridManager();
	manager.deleteRow(rowindex);
	grid.loadData();
}

//验证货品表数据和货品数据转json提交
var header = {'prodBarCode':'货品条码','saleType':'销售类型','inventoryType':'库存类型','salePrice':'含税零售价','unSalePrice':"未税零售价",'buyNum':'最低订货数量 ','casePakgSize':'箱包装规格','prodUnit':'单位'};
var prod = true;
function getProd(){
	prod = true;
	var manager = $("#maingrid").ligerGetGridManager();
	var data = manager.getData();
	var spec = [];
	$(".box").each(function(){
		if(this.checked){
			spec.push($(this).val());
		}
	});
	
	if(data.length < 1){
		$.ligerDialog.warn("请添加货品");
		prod = false;
		return false;
	}
	
	$.each(data,function(index,item){
		$.each(item,function(key,val){
			if(val == null || val == "" || val == "0.00" || val == "0"){
				var er = "";
				if(key != "prodRate" && key != "prodUnit"){
					if(data[index].prodBarCode) er += "货品   "+data[index].prodBarCode+" ";
					er += header[key]+"不能为空";
					$.ligerDialog.warn(er);
					prod = false;
					return false;
				}
			}
		});
		if(!prod) return prod;		
		var specStr ="";
		if(spec.length == 0){
			$.ligerDialog.warn("请添加货品规格");
			prod = false;
			return false;
		}
		$.each(spec,function(k,v) {
			if(specStr != "") specStr += ",";
			if(item[v] != null && item[v] != ""){
				specStr += v+"-"+item[v];
			}else{
				$.ligerDialog.warn("请选择货品"+data[index].prodBarCode+"规格");
				prod = false;
				return false;
			}
		});
		if(!prod) return prod;
		data[index].specStr = specStr;
	});
	document.getElementById("productString").value = JSON.stringify(data);
	//$.ligerDialog.warn(JSON.stringify(data));
}

var codeid = -1;
//验证货品编码
function valProdBarCode(rowcell, value){
	codeid = -1;
	var data = grid.getData();
	for ( var i = 0; i < data.length; i++) {
		if(data[i]["prodBarCode"] == value && data[i]["prodBarCode"] != ""){
			$.ligerDialog.warn("该货品条码已存在，请重新输入！");
			var manager = $("#maingrid").ligerGetGridManager();
			var row = manager.getSelectedRow();
			codeid = row.__index;
		}
	}
	
	$.post(
			basePath + '/product/commoditymgt/validationRepeatProdBarCode.do',
			{prodBarCode : value},
		 	function(data) {
				if(data == "success"){
					$.ligerDialog.warn("该货品条码已存在，请重新输入！");
					var manager = $("#maingrid").ligerGetGridManager();
					var row = manager.getSelectedRow();
					codeid = row.__index;
				};
			}
	);
}

</script>
<script type="text/javascript">

	var basePath="${BasePath}";
	$(function() {
		//初始加载分类
		parentCat("0");
	});
	//获取分类
	function getProCat(o){
		$("select[name=level]").eq($(o).index()).nextAll().remove();
		
		if(o.value == "" || o.value == null){
			$("#catNo").val($("select[name=level]").eq($(o).index()-1).val());
		}else{
			$("#catNo").val(o.value);
		}
		
		getBrandListByCatNo($("#catNo").val());
		showSpecification($("#catNo").val());
		var columns = [];
		columns = grid.columns;
		columns.splice(9, columns.length-10);
		grid.set("columns",columns);
		grid.loadData();
		
		if(o.value == "0") return false;
		sonCat(o.value);
	}
		

	
	//选择分类显示对应的品牌
	function getBrandListByCatNo(catNo){
		$("#brandNo").empty();// 清空下来框
        $("#brandNo").append("<option value='0'>请选择品牌</option>");
		
		$.post('${BasePath}/product/commoditymgt/get_brand_list.do', {
			catNo : catNo
		}, 
		function(data) {
			if(data != ""){
				var obj=$.parseJSON(data);
				for(var i in obj){
					var option = "<option value='"+obj[i].brandNo +"'>"+obj[i].brandName+"</option>";
                    $("#brandNo").append(option);
				 };
			}
		});
	}
	
	function showSpecification(catNo) {
		//分类显示对应的规格
		$("#choosespecDiv").empty();
		$.post('${BasePath}/product/specmgt/getSpecificationListByCatNo.do', {
			catNo : catNo
		}, 
		function(data) {
			if(data != ""){
				var obj=$.parseJSON(data);
				var Specification = "";
				for(var i in obj){
					Specification += "<input class='box' type='checkbox' name='"+obj[i].specName+"' value='"+obj[i].specNo+"' onclick='choosekbox(this)'>";
					Specification += obj[i].specName;
				};
				$("#choosespecDiv").append(Specification);
			};
		});
		//分类显示对应的规格结束
	};
	
	function choosekbox(o) {
		
		if (o.checked) {
			var SpecificationData = new Array();
			$.post('${BasePath}/product/specmgt/getSpecificationListBySpecNo.do', {
				specNo : o.value
			}, 
			function(data) {
				if(data != ""){
					var obj = $.parseJSON(data);
					obj = obj.specValOptions;
					SpecificationData.push({"optionNo":"","text":"请选择"});
					for(var i in obj){
						SpecificationData.push({"optionNo":obj[i].optionNo,"text":obj[i].optionName});
					};
				}else{
					return;
				};
			});
			var display = o.name;
			var name = o.value;
			var column ={ 	display: display, name: name,
							editor: { type: 'select', data: SpecificationData, valueField: "optionNo" },
							render: function (item,index,value){
								if(value == null || value == "") return "请选择";
								for ( var i = 0; i < SpecificationData.length; i++) {
									var sp = SpecificationData[i];
									if(sp.optionNo == value){
										return sp.text;		
									}	
								}
							}
						};
			var columns = grid.columns;
			columns.splice(columns.length-1,0,column);
			grid.set("columns",columns);
			grid.loadData();
		} else {
			var col = [];
			col = grid.columns;
			for ( var i = 0; i < col.length; i++) {
				
				var val = o.value;
				var name = col[i].name;
				if(name == val){
					col.splice(i, 1);
				}
			}
			grid.set("columns",col);
			grid.loadData();
		}
	}
	
//from提交
$(function ()
		{
			//validate
		    $.metadata.setType("attr", "validate");
		    var v = $("form").validate({
		        errorPlacement: function (lable, element)
		        {
		        	lable.ligerHideTip();
		            if (element.hasClass("l-textarea"))
		            {
		            	$("form textarea").ligerHideTip();
		                element.ligerTip({ content: lable.html(), target: element[0] }); 
		            }
		            else if (element.hasClass("l-text-field"))
		            {
		                element.parent().ligerTip({ content: lable.html(), target: element[0] });
		            }
		            else
		            {
		                lable.appendTo(element.parents("td:first").next("td"));
		            }
		            
		        },
		        submitHandler:function()
		        {
		        	$("form .l-text,.l-textarea").ligerHideTip();
		        	if($("#catNo").val()=="0"){
		        		$.ligerDialog.warn("请先选择分类!");
		        		return false;
		        	}
		        	if($("#brandNo").val()=="0"){
		        		$.ligerDialog.warn("请先选择品牌!");
		        		return false;
		        	}
					getProd();
		            if(!prod) return prod;
		            var options = {
		            		type: 'POST',
		            		beforeSend: function(){
		            			$("#form1").find(":submit,:button").attr("disabled", true);
		            		},
		            		success: function(data){
		            			if(data=="success") {
		            				window.parent.f_tip('新增成功');
		            				close_liger_tab();
		            			} else {
		            				window.parent.f_tip('新增失败');
		            			}
		            		}
		            	}, $form1 = $("#form1");
		           $form1.ajaxSubmit(options);
		           return false;
		        }
		    });
		}); 
	
	
// 取消
$("#tests").click(function() {
	close_liger_tab();
});
</script>
</body>
</html>